package com.woniu.woniu_bx.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.woniu.woniu_bx.exception.PasswordExistException;
import com.woniu.woniu_bx.exception.UserExistsException;
import com.woniu.woniu_bx.mapper.UserMapper;
import com.woniu.woniu_bx.pojo.PageBean;
import com.woniu.woniu_bx.pojo.User;
import com.woniu.woniu_bx.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author : 王泰元
 * @description: 用户 ServiceImpl
 * @date : 2022/8/27 15:09
 */
@Transactional
@Service

public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Override
    public void updateUserBaseInfo(User user) {
        userMapper.updateUserBaseInfo(user);
    }

    /**
     * 保存用户
     *
     * @param user 用户
     * @author: 王泰元
     */
    @Override
    public void addUser(User user) {

        // 根据账户查询用户，判断用户是否已存在
        if (getByAccount(user.getAccount()) != null) {
            throw new UserExistsException("账户已存在");
        }

        // 密码加密，来自 security 的 BCryptPasswordEncoder
        BCryptPasswordEncoder passwordEncoder = new BCryptPasswordEncoder();
        user.setPassword(passwordEncoder.encode(user.getPassword()));

        // 设置注册时间
        user.setRegTime(new SimpleDateFormat("yyyy-MM-dd HH:mm:ss").format(new Date()));

        // 设置状态
        user.setStatus("y");

        // 陪玩认证状态
        user.setAuthPw("n");

        // 设置默认头像
        user.setAvr("avatar30043.png");

        // 如果个性签名为空，设置默认签名
        if (!StringUtils.hasLength(user.getSignature())) {
            user.setSignature("系统默认签名，送给每一个小可爱");

        }

        // 将用户加入到数据库中
        userMapper.insert(user);
    }

    @Override
    public User getUserById(Integer id) {
        return userMapper.getUserById(id);
    }


    /**
     * 根据账户查询用户
     *
     * @param account 账户
     * @return 返回用户 pojo 对象
     */
    @Override
    @Transactional(readOnly = true)
    public User getByAccount(String account) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("account", account);
        return userMapper.selectOne(queryWrapper);
    }


    /**
     * 根据手机号查询用户
     *
     * @param phone 手机号
     * @return 返回用户 pojo 对象
     */
    @Override
    @Transactional(readOnly = true)
    public User getByPhone(String phone) {
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("phone", phone);
        return userMapper.selectOne(queryWrapper);
    }

    /**
     * 得到关注列表，只查询 id、头像、昵称，其它详细信息可根据 id 再次查询
     *
     * @param userId 用户id
     * @return 关注列表集合
     */
    @Override
    public List<User> getLikesById(Integer userId) {
        return userMapper.getLikesById(userId);
    }

    /**
     * 得到粉丝列表，只查询 id、头像、昵称，其它详细信息可根据 id 再次查询
     *
     * @param userId 用户id
     * @return 粉丝列表集合
     */
    @Override
    public List<User> getFansById(Integer userId) {
        return userMapper.getFansById(userId);
    }

    @Override
    public List<User> getLikesEachById(Integer id) {
        return userMapper.getLikesEachById(id);
    }

    @Override
    public List<User> getFansEachById(Integer id) {
        return userMapper.getFansEachById(id);
    }

    @Override
    public PageBean<User> getByPage(User user, Integer pageNum, Integer pageSize) {
        PageBean<User> pageBean = new PageBean<>();
        Page<Object> page = PageHelper.startPage(pageNum, pageSize);
        List<User> users = userMapper.getByCondition(user);
        users.forEach(u -> {
            u.setLikesCount(userMapper.getLikesCount(u.getId()));
            u.setFansCount(userMapper.getFansCount(u.getId()));
        });
        pageBean.setCurrPage(pageNum);
        pageBean.setData(users);
        pageBean.setCurrPageSize(users.size());
        pageBean.setPageSize(pageSize);
        pageBean.setTotalPages(page.getPages());
        pageBean.setTotalNums((int) page.getTotal());
        return pageBean;
    }

    @Override
    public void updateByCondition(User user) {
        if (user.getId() == null) {
            throw new NullPointerException("id不能为空");
        }
        userMapper.update(user);
    }

    @Override
    public List<String> getUserImagesById(Integer id) {
        return userMapper.getUserImagesById(id);
    }

    /**
     * @param id       用户id
     * @param password 用户原密码
     * @param newpwd   用户新密码
     */
    @Override
    public void updateUserPwd(Integer id, String password, String newpwd) {
        User user = userMapper.selectById(id);
        // 判断用户输入的原密码是否正确
        if (!password.equals(user.getPassword())) {
            throw new PasswordExistException("原密码不正确");
        } else if (newpwd.equals(user.getPassword())) {
            throw new PasswordExistException("新密码不能与原密码相同");
        } else {
            userMapper.updateUserPwd(id, newpwd);
        }
    }

    /**
     * 批量插入图片
     *
     * @param userId  用户 id
     * @param imgList 用户陪玩图片集合（String 地址）
     */
    @Override
    public void addUserImg(Integer userId, List<String> imgList) {
        for (String img : imgList) {
            userMapper.addUserImg(userId, img);
        }
    }

    @Override
    public BigDecimal getAllOrderMoneyByUid(Integer uid) {
        return userMapper.getAllOrderMoneyByUid(uid);
    }


    @Override
    public void careSomebody(Integer myId, Integer otherId) {
        if (myId.equals(otherId)) {
            throw new RuntimeException("不能关注自己");
        }
        Integer count = userMapper.findEach(otherId, myId);
        if (count == 1) {
            userMapper.careSomebody(myId, otherId, 'y');
            userMapper.updateEach(otherId, myId, 'y');
        } else {
            userMapper.careSomebody(myId, otherId, 'n');
        }

    }

    @Override
    public void cancelCare(Integer myId, Integer otherId) {
        Integer count = userMapper.findEach(otherId, myId);
        if (count == 1) {
            userMapper.cancelCare(myId, otherId);
            userMapper.updateEach(otherId, myId, 'n');
        } else {
            userMapper.cancelCare(myId, otherId);
        }
    }

    /**
     * 卖家提现后直接清零
     *
     * @param userId
     */
    @Override
    public void withdrawPwMoney(Integer userId) {
        userMapper.withdrawPwMoney(userId);
    }

    @Override
    public Integer getLikesCount(Integer id) {
        Integer likesCount = userMapper.getLikesCount(id);
        return likesCount;
    }

    @Override
    public Integer getFansCount(Integer id) {
        Integer fansCount = userMapper.getFansCount(id);
        return fansCount;
    }

    @Override
    public Integer getTotalSaleNums(Integer id) {
        return userMapper.getUserTotalSaleNums(id);
    }

    /**
     * 删除图片
     * @param url
     */
    @Override
    public void deleteImage(String url) {
        userMapper.deleteImage(url);
    }

    /**
     * 是否关注对方
     * @param myId
     * @param openUserId
     * @return
     */
    @Override
    public boolean careUser(Integer myId, Integer openUserId) {
        if(userMapper.careUser(myId,openUserId)!=0){
            return true;
        }
        return false;
    }
}
